package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.bbs.entity.BBSPost;
import com.bbs.entity.BBSPostCollect;
import com.bbs.entity.BBSUser;
import com.bbs.mapper.IBBSPostCollectMapper;
import com.bbs.mapper.IBBSPostMapper;
import com.bbs.mapper.IBBSUserMapper;
import com.bbs.service.IBBSPostCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BBSPostCollectServiceImpl implements IBBSPostCollectService {

    @Autowired
    private IBBSPostCollectMapper bbsPostCollectMapper;

    @Autowired
    private IBBSPostMapper bbsPostMapper;

    @Autowired
    private IBBSUserMapper bbsUserMapper;

    /*
     * 添加收藏帖子
     * */
    @Override
    @Transactional
    public Boolean addCollectRecord(Long userId, Long postId) {
        // 检查该用户和帖子是否已经存在收藏记录
        BBSPostCollect bbsPostCollect = bbsPostCollectMapper.selectOne(
                new LambdaQueryWrapper<BBSPostCollect>()
                        .eq(BBSPostCollect::getPostId, postId)
                        .eq(BBSPostCollect::getUserId, userId)
        );

        BBSPost bbsPost = bbsPostMapper.selectOne(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPostId, postId)
        );

        BBSUser bbsCollectUser = bbsUserMapper.selectOne(
                new LambdaQueryWrapper<BBSUser>()
                        .eq(BBSUser::getUserId,userId)
        );
        if (bbsCollectUser.getUserStatus() == 1 || bbsCollectUser == null) {
            //账号被封禁
            return false;
        }

        if (bbsPostCollect != null) {
            // 记录存在，返回true（表示已经收藏）
            return true;
        }
        //创建一个新的收藏记录
        bbsPostCollect = new BBSPostCollect();
        bbsPostCollect.setPostId(postId);
        bbsPostCollect.setUserId(userId);

        int insert = bbsPostCollectMapper.insert(bbsPostCollect);

        //更新帖子的收藏数量
        int update = bbsPostMapper.update(
                null,
                new LambdaUpdateWrapper<BBSPost>()
                        .eq(BBSPost::getPostId, bbsPost.getPostId())
                        .set(BBSPost::getPostCollects, bbsPost.getPostCollects() + 1)
        );

        //插入新的收藏，检查是否插入成功
        if(insert > 0 && update > 0){
            return true;
        }
        return false;
    }

    /*
     * 取消帖子收藏
     * */
    @Override
    @Transactional
    public Boolean deleteCollectRecord(Long userId, Long postId) {
        // 检查该用户和帖子是否存在收藏记录
        BBSPostCollect bbsPostCollect = bbsPostCollectMapper.selectOne(
                new LambdaQueryWrapper<BBSPostCollect>()
                        .eq(BBSPostCollect::getPostId, postId)
                        .eq(BBSPostCollect::getUserId, userId)
        );
        if (bbsPostCollect == null) {
            return false;
        }

        // 通过postId查询帖子
        BBSPost bbsPost = bbsPostMapper.selectOne(
                new LambdaQueryWrapper<BBSPost>()
                        .eq(BBSPost::getPostId, postId)
        );
        System.out.println("bbsPostCollectNum: " + bbsPost.getPostComments());

        BBSUser bbsCollectUser = bbsUserMapper.selectOne(
                new LambdaQueryWrapper<BBSUser>()
                        .eq(BBSUser::getUserId,userId)
        );
        if (bbsCollectUser.getUserStatus() == 1 || bbsCollectUser == null) {
            //账号被封禁
            return false;
        }

        // 删除帖子收藏记录
        int delete = bbsPostCollectMapper.delete(
                new LambdaUpdateWrapper<BBSPostCollect>()
                        .eq(BBSPostCollect::getPostId, postId)
                        .eq(BBSPostCollect::getUserId, bbsCollectUser.getUserId())
        );

        int update = bbsPostMapper.update(null,
                new UpdateWrapper<BBSPost>()
                        .eq("post_id", bbsPost.getPostId())
                        .set("post_collects", bbsPost.getPostCollects() - 1)
        );
        if(update > 0 && delete > 0){
            return true;
        }

        return false;
    }

    /*
     * 验证用户是否收藏了帖子
     * */
    @Override
    public Boolean validUserCollect(Long userId, Long postId) {
        BBSPostCollect bbsPostCollect = bbsPostCollectMapper.selectOne(
                new LambdaQueryWrapper<BBSPostCollect>()
                        .eq(BBSPostCollect::getPostId, postId)
                        .eq(BBSPostCollect::getUserId, userId)
        );
        if (bbsPostCollect == null) {
            return false;
        }
        return true;
    }

    //获取收藏的帖子列表
    @Override
    public List<BBSPost> getCollectRecordsByUserId(Long userId) {

        List<BBSPostCollect> bbsPostCollects = bbsPostCollectMapper.selectList(
                new LambdaQueryWrapper<BBSPostCollect>()
                        .eq(BBSPostCollect::getUserId, userId)
        );

        if (!CollectionUtils.isEmpty(bbsPostCollects)) {
            List<Long> postIds = bbsPostCollects.stream()//使用Java Stream API从收藏记录中提取帖子的ID，并收集到一个列表中
                    .map(BBSPostCollect::getPostId)// 将每个BBSPostCollect对象映射为其帖子ID
                    .collect(Collectors.toList());// 收集结果到List<Long>中
            //根据帖子的id获取帖子列表
            List<BBSPost> bbsPosts = bbsPostMapper.selectList(
                    new LambdaQueryWrapper<BBSPost>()
                            .in(BBSPost::getPostId, postIds)
            );
            return bbsPosts;
        }

        return null;
    }
}
